/**
 * WClient H5工具集
 * 2018.10
 * 
 * 需置于body内的页底
 */
var wclient = new (function(){
	
	(function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);
	
	function isArray(o){
		return Object.prototype.toString.call(o)=='[object Array]';
	}
	
	function loadScript(src, callback) {
		var script = document.createElement('script'),
			head = document.getElementsByTagName('head')[0];
		script.type = 'text/javascript';
		script.charset = 'UTF-8';
		script.src = src;
		if (script.addEventListener) {
			script.addEventListener('load', function () {
				callback();
			}, false);
		} else if (script.attachEvent) {
			script.attachEvent('onreadystatechange', function () {
				var target = window.event.srcElement;
				if (target.readyState == 'loaded') {
					callback();
				}
			});
		}
		head.appendChild(script);
	}
	
	var ua = navigator.userAgent;
    var isWeixin = this.isWeixin = /MicroMessenger/.test(ua);	// 检测是否是微信环境
    var isAlipay = this.isAlipay = /AlipayClient/.test(ua);		// 检测是否是支付宝环境
    var isCodingman = this.isCodingman = /CodingMan/.test(ua);		// 检测是否是CodingMan环境
    var isCodingmanDevTools = /codingmandevtools/.test(ua);		// 检测是否是CodingMan测试环境
    
    if(isCodingman){
    	$(".cmapp-hide").hide();
    }

	//SHA1算法导入
	var hexcase=0;var b64pad="";var chrsz=8;function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length*chrsz))}function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length*chrsz))}function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length*chrsz))}function hex_hmac_sha1(key,data){return binb2hex(core_hmac_sha1(key,data))}function b64_hmac_sha1(key,data){return binb2b64(core_hmac_sha1(key,data))}function str_hmac_sha1(key,data){return binb2str(core_hmac_sha1(key,data))}function sha1_vm_test(){return hex_sha1("abc")=="a9993e364706816aba3e25717850c26c9cd0d89d"}function core_sha1(x,len){x[len>>5]|=128<<(24-len%32);x[((len+64>>9)<<4)+15]=len;var w=Array(80);var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;var e=-1009589776;for(var i=0;i<x.length;i+=16){var olda=a;var oldb=b;var oldc=c;var oldd=d;var olde=e;for(var j=0;j<80;j++){if(j<16){w[j]=x[i+j]}else{w[j]=rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1)}var t=safe_add(safe_add(rol(a,5),sha1_ft(j,b,c,d)),safe_add(safe_add(e,w[j]),sha1_kt(j)));e=d;d=c;c=rol(b,30);b=a;a=t}a=safe_add(a,olda);b=safe_add(b,oldb);c=safe_add(c,oldc);d=safe_add(d,oldd);e=safe_add(e,olde)}return Array(a,b,c,d,e)}function sha1_ft(t,b,c,d){if(t<20){return(b&c)|((~b)&d)}if(t<40){return b^c^d}if(t<60){return(b&c)|(b&d)|(c&d)}return b^c^d}function sha1_kt(t){return(t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514}function core_hmac_sha1(key,data){var bkey=str2binb(key);if(bkey.length>16){bkey=core_sha1(bkey,key.length*chrsz)}var ipad=Array(16),opad=Array(16);for(var i=0;i<16;i++){ipad[i]=bkey[i]^909522486;opad[i]=bkey[i]^1549556828}var hash=core_sha1(ipad.concat(str2binb(data)),512+data.length*chrsz);return core_sha1(opad.concat(hash),512+160)}function safe_add(x,y){var lsw=(x&65535)+(y&65535);var msw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&65535)}function rol(num,cnt){return(num<<cnt)|(num>>>(32-cnt))}function str2binb(str){var bin=Array();var mask=(1<<chrsz)-1;for(var i=0;i<str.length*chrsz;i+=chrsz){bin[i>>5]|=(str.charCodeAt(i/chrsz)&mask)<<(32-chrsz-i%32)}return bin}function binb2str(bin){var str="";var mask=(1<<chrsz)-1;for(var i=0;i<bin.length*32;i+=chrsz){str+=String.fromCharCode((bin[i>>5]>>>(32-chrsz-i%32))&mask)}return str}function binb2hex(binarray){var hex_tab=hexcase?"0123456789ABCDEF":"0123456789abcdef";var str="";for(var i=0;i<binarray.length*4;i++){str+=hex_tab.charAt((binarray[i>>2]>>((3-i%4)*8+4))&15)+hex_tab.charAt((binarray[i>>2]>>((3-i%4)*8))&15)}return str}function binb2b64(binarray){var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var str="";for(var i=0;i<binarray.length*4;i+=3){var triplet=(((binarray[i>>2]>>8*(3-i%4))&255)<<16)|(((binarray[i+1>>2]>>8*(3-(i+1)%4))&255)<<8)|((binarray[i+2>>2]>>8*(3-(i+2)%4))&255);for(var j=0;j<4;j++){if(i*8+j*6>binarray.length*32){str+=b64pad}else{str+=tab.charAt((triplet>>6*(3-j))&63)}}}return str};
	
	
	// 系统路径
	this.baseURL = "";
	this.wclientUriPath = "/m/wclient";	// /m/wclient, /m/events/wclient（通过nginx映射，确保指向到同一服务）
	
	// TODO 根据URL组件规则，自动适配其映射的 组件转发路径下的wclient映射路径
	if(location.href.indexOf("m.weapi.com/page/events/")>0
			|| location.href.indexOf("m.weapi.com/m/events/")>0){
	 	this.wclientUriPath = "/events/m/wclient";
	} else if(location.href.indexOf("m.weapi.com/page/events-test/")>0
			|| location.href.indexOf("m.weapi.com/m/events-test/")>0){
	 	this.wclientUriPath = "/m/events-test/wclient";
	} else if(location.href.indexOf("m.weapi.com/ncpa-events/page/events/")>0){
	 	this.wclientUriPath = "/ncpa-events/m/wclient";
	} else if(location.href.indexOf("m.weapi.com/page/timinglottery/")>0
			|| location.href.indexOf("m.weapi.com/m/timinglottery/")>0){
	 	this.wclientUriPath = "/m/timinglottery/wclient";
	} else if(location.href.indexOf("m.weapi.com/m/pointmall/")>0){
	 	this.wclientUriPath = "/m/pointmall/wclient";
	}
	
	// 当前登录的用户信息
	this.wuser = null;
	
	// 是否开启跨域模式（单体项目时，无需开启；多组件项目时，由前端静态页面设置开启。开启后通过JSONP模式调用接口，自动携带access_token参数）
	this.crossdomain = false;
	
	function _ajax(url, data, success, error){
		if(typeof(url)=="object"){
			var config = url;
			url = config.url;
			data = config.data;
			success = config.success;
			// type = config.type;
			error = config.error;
		}
		
		if(wclient.crossdomain){
			var jsonpURL = url;
			jsonpURL += jsonpURL.indexOf("?")>0 ? "&callback=?" : "?callback=?";
			
			$.ajax({
				url : jsonpURL,
				data : data,
				type : "GET",
				dataType : "jsonp",
				success : success
			});
		} else {
			$.ajax({
				url : url,
				data : data,
				type : "GET",
				dataType : "json",
				success : success
			});
		}
	}
	this.ajax = _ajax;
	
	// 获取用户授权（已支持多渠道）
	this.connect = function(moduleid, callback){
		
		var loadwuserRequestData = { moduleid: moduleid };
		if(wclient.crossdomain)
			loadwuserRequestData.getaccesstoken = "1";	// 跨域应用时，申请获取跨域access_token
		
		wclient.view.showLoading(1000, "登录中");
		var self = this;
		_ajax({
			url : self.baseURL + self.wclientUriPath + '/connect/ajax/loadwuser',	// /m/wclient/connect/ajax/loadwuser
			data : loadwuserRequestData,
			// type : "POST",
			// dataType : "json",
			success : function(data) {
				if(data.code=="A00004"){
					location.href = self.baseURL + self.wclientUriPath + "/connect/connectmoduleuserbyh5?moduleid=" + moduleid + "&redirect_uri=" + encodeURIComponent(location.href);
					return;
				} else if(data.code=="A00005"){
					wclient.view.hideLoading();
					self.view.showErrorPage(data.errmsg);
				} else if(data.code=="A00006"){
					wclient.view.hideLoading();
					
					// 返回业务，回调
					self.wuser = data.wuser;
					callback && callback(data);
					
					// 隐藏遮盖，显示页面
					$(".page-container").show();
				} else {
					wclient.view.hideLoading();
					self.view.showErrorPage("发生错误：" + data.errmsg);
				}
			}
		});
	};
	
	// 多渠道初始状态
	this.jssdk_inited = false;
	this.weixin_jssdk_inited = false;
	this.codingman_jssdk_inited = false;
	
	// 初始化JSSDK操作权限（多渠道）
	this.initJSSDK = function(param, callback){
		
		// 默认参数
		param.mpbrokerBaseurl = param.mpbrokerBaseurl || "https://weapi.com";
		
		if(isWeixin){
			if(!param.mpid || !param.mpbrokerBaseurl){
				console && console.log("initJSSDK fail(weixin)! param=" + JSON.stringify(param));
				return;
			}
			
			if(!window.jWeixin || !window.jWeixin.config){
				loadScript("//res.wx.qq.com/open/js/jweixin-1.4.0.js", function(){
					wclient.initJSSDK(param, callback);
				});
				return;
			}
			
			if(!window.jsticket){
				var mpbJssdkTicketURL = param.mpbrokerBaseurl + "/api/jssdk/ticket?mpid=" + param.mpid;
				loadScript(mpbJssdkTicketURL, function(){
					if(!window.jsticket){
						console && console.log("initJSSDK fail(weixin)! invalid jssdk-ticket! param=" + JSON.stringify(param));
						return;
					}
					
					wclient.initJSSDK(param, callback);
				});
				return;
			}
			
			var addJsApis = param.weixinJsApiList;
			var share_url=location.href;
			var timestamp=new Date().getTime()+'';
			var nonceStr=timestamp+parseInt(Math.random()*100000)+'';
			var jsapi_ticket = window.jsticket || "";
			var strSHA1=hex_sha1("jsapi_ticket=" + jsapi_ticket + "&noncestr="+nonceStr+"&timestamp="+timestamp+"&url="+share_url);//SHA1加密
			var wx = window.jWeixin && window.jWeixin.ready ? window.jWeixin : window.wx2;
			var checkjsapi = location.href.indexOf("checkjsapi")>0;
			
			var jsApiList = [
				'checkJsApi',
				'onMenuShareTimeline',
				'onMenuShareAppMessage',
				'onMenuShareQQ',
				'onMenuShareWeibo',
				'openLocation',
				'getLocation',
				'getNetworkType',
				'showOptionMenu'
			];
			if(isArray(addJsApis)){
				for(var n in addJsApis)
					jsApiList.push(addJsApis[n]);
			} else if(typeof addJsApis === 'string'){
				jsApiList.push(addJsApis);
			}
			
			jWeixin.config({
				debug: checkjsapi,
				appId: window.jsappid,
				timestamp: timestamp,
				nonceStr: nonceStr,
				signature: strSHA1,
				jsApiList: jsApiList
			});
			
			// 标记微信JSSDK已初始化
			this.weixin_jssdk_inited = true;
			this.jssdk_inited = false;
			
			jWeixin.ready(function () {
				var checkjsapi = location.href.indexOf("checkjsapi")>0;
				if(checkjsapi){
					// 1 判断当前版本是否支持指定 JS 接口，支持批量判断
					jWeixin.checkJsApi({
						jsApiList: [
						  'getNetworkType',
						  'onMenuShareTimeline',
						  'onMenuShareAppMessage'
						],
						success: function (res) {
							alert(JSON.stringify(res));
						}
					});
				}
				
				callback && callback();
			});
		} else if(isCodingman){
			
			if(isCodingmanDevTools && !window.__codingman_jsapi){
				loadScript("//m.weapi.com/m/wclient/js/jcodingman-devtools-1.0.0.js", function(){
					wclient.initJSSDK(param, callback);
				});
				return;
			}
			
			if(!window.cm){
				loadScript("//m.weapi.com/m/wclient/js/jcodingman-1.0.0.js", function(){
					// 标记CM-JSSDK已初始化
					this.codingman_jssdk_inited = true;
					this.jssdk_inited = false;
					
					callback && callback();
				});
			} else {
				// 标记CM-JSSDK已初始化
				this.codingman_jssdk_inited = true;
				this.jssdk_inited = false;
				
				callback && callback();
			}
		} else
			console && console.log("initJSSDK, ua no support!");
		
		return this;
	};
	
	// 配置分享信息（多渠道）
	this.setupShare = function(sharedata, callback){
		if(isWeixin){
			if(sharedata){
				sharedata.tTitle = sharedata.tTitle || sharedata.title;
				sharedata.tContent = sharedata.tContent || sharedata.desc;
				sharedata.sendFriendLink = sharedata.sendFriendLink || sharedata.link;
				sharedata.imgUrl = sharedata.imgUrl || sharedata.imgurl;
				
				this.initWeixinShare(sharedata);
			} else {
				jWeixin.hideOptionMenu();
			}
		} else if(isCodingman){
			window.cm && window.cm.setupShare(sharedata, callback);
		} else
			console && console.log("setupShare, ua no support!");
	};
	
	// 添加微信卡券（多渠道）
	this.addWXCard = function(cardList, callback){
		if(isWeixin){
			jWeixin.addCard({ cardList: cardList, success: callback });
		} else if(isCodingman){
			window.cm && window.cm.addWXCard(cardList, callback);
		} else
			console && console.log("addWXCard, ua no support!");
	};
	
	// 关闭webview窗口（多渠道）
	this.closeWindow = function(){
		if(isWeixin)
			jWeixin.closeWindow();
		else if(isCodingman)
			window.cm && window.cm.closeWindow();
		else
			console && console.log("closeWindow, ua no support!");
	};
	
	// 设置微信分享
	this.initWeixinShare = function(sharedata, addJsApis){
		if(!isWeixin)
			return;
		
		// 兼容老页面，未执行initJSSDK时，自动执行
		if(!this.weixin_jssdk_inited){
			this.initJSSDK({"weixinJsApiList":addJsApis});
		}

		jWeixin.ready(function () {
			var checkjsapi = location.href.indexOf("checkjsapi")>0;
			if(checkjsapi){
				// 1 判断当前版本是否支持指定 JS 接口，支持批量判断
				jWeixin.checkJsApi({
					jsApiList: [
					  'getNetworkType',
					  'onMenuShareTimeline',
					  'onMenuShareAppMessage'
					],
					success: function (res) {
						alert(JSON.stringify(res));
					}
				});
			}
			
			jWeixin.showOptionMenu();
		
			// 2. 分享接口
			// 2.1 监听“分享给朋友”，按钮点击、自定义分享内容及分享结果接口
			jWeixin.onMenuShareAppMessage({
				title : sharedata.tTitle,
				desc : sharedata.tContent,
				link : sharedata.sendFriendLink,
				imgUrl : sharedata.imgUrl,
				type : '', // 分享类型,music、video或link，不填默认为link
				dataUrl : '', // 如果type是music或video，则要提供数据链接，默认为空
				success : function() {
					if(window._wxsharecallback)
						window._wxsharecallback('friends');
					//if(shareCallback)
					//	shareCallback('friend');
					
					if(checkjsapi)
						alert('分享朋友成功');
				},
				cancel : function() {
					if(checkjsapi)
						alert('分享朋友失败');
				}
			});
	
			// 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
			jWeixin.onMenuShareTimeline({
				title : sharedata.tTitle,
				link : sharedata.sendFriendLink,
				imgUrl : sharedata.imgUrl,
				success : function() {
					if(window._wxsharecallback)
						window._wxsharecallback('timeline');
					//if(shareCallback)
					//	shareCallback('friends');
					//alert('分享朋友圈成功');
				},
				cancel : function() {
					//alert('分享朋友圈失败');
				}
			});
	
			// 2.4 监听“分享到微博”按钮点击、自定义分享内容及分享结果接口
			jWeixin.onMenuShareWeibo({
				title : sharedata.tTitle,
				desc : sharedata.tContent,
				link : sharedata.sendFriendLink,
				imgUrl : sharedata.imgUrl,
				success : function() {
					if(window._wxsharecallback)
						window._wxsharecallback('weibo');
					//if(shareCallback)
					//	shareCallback('weibo');
					//alert('分享微博成功');
				},
				cancel : function() {
					//alert('分享微博失败');
				}
			});
		});
	};
	



	
	var loadingTimer;
	
	// 界面工具（加载中、弹窗等）
	this.view = {
		inited : false,
		
		init : function(){
			var HTML = `
				<!-- loading toast -->
				<div id="loadingToast" class="weui_loading_toast" style="display:none;">
				    <div class="weui-mask_transparent weui_mask_transparent"></div>
				    <div class="weui-toast weui_toast">
				        <div class="weui-loading weui-icon_toast weui_loading">
				            <div class="weui_loading_leaf weui_loading_leaf_0"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_1"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_2"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_3"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_4"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_5"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_6"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_7"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_8"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_9"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_10"></div>
				            <div class="weui_loading_leaf weui_loading_leaf_11"></div>
				        </div>
				        <p class="weui-toast__content">加载中</p>
				    </div>
				</div>
	
				<!--BEGIN msgdialog-->
				<div class="weui_dialog_alert" id="msgdialog" style="display:none;">
				    <div class="weui-mask weui_mask"></div>
				    <div class="weui-dialog weui_dialog">
				        <div class="weui-dialog__hd weui_dialog_hd"><strong class="weui-dialog__title"></strong></div>
				        <div class="weui-dialog__bd weui_dialog_bd">弹窗内容，告知当前页面信息等</div>
				        <div class="weui-dialog__ft weui_dialog_ft">
				            <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary weui_btn_dialog primary">确定</a>
				        </div>
				    </div>
				</div>
				<!--END msgdialog-->
	
				<!--BEGIN msgdialog-->
				<div class="weui_dialog_alert" id="msgdialog2" style="display:none;">
				    <div class="weui-mask weui_mask"></div>
				    <div class="weui-dialog weui_dialog">
				        <div class="weui-dialog__hd weui_dialog_hd"><strong class="weui-dialog__title"></strong></div>
				        <div class="weui-dialog__bd weui_dialog_bd">弹窗内容，告知当前页面信息等</div>
				        <div class="weui-dialog__ft weui_dialog_ft">
				            <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_default weui_btn_dialog">关闭</a>
				            <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary weui_btn_dialog primary">继续</a>
				        </div>
				    </div>
				</div>
				<!--END msgdialog-->
			`;
			$("body").append(HTML);
			this.inited = true;
		},
			
		showErrorPage : function(errmsg, desc){
			var HTML = '<div class="wclientmobile-bg bg"><div class="cont"><div class="c1"><img src="/mframework/img/opps.png"></div><h2 class="errmsg">拒绝访问</h2><div class="desc"></div></div></div>';
			var pageJQ = $(HTML);
			pageJQ.find(".errmsg").html(errmsg);
			pageJQ.find(".desc").html(desc || "");
			pageJQ.appendTo("body");
		},
	
		showLoading : function(delayTime, loadingmsg){
			$('#loadingToast .weui_toast_content,#loadingToast .weui-toast__content').html(loadingmsg || "加载中");	// 不超过5个字
			
			if(!delayTime){
				$('#loadingToast').show();
				return;
			}
			
			loadingTimer = setTimeout(function(){
				$('#loadingToast').show();
			}, delayTime===true ? 1000 : delayTime);
		},

		hideLoading : function(){
			clearTimeout(loadingTimer);
			$('#loadingToast').hide();
		},

		// 弹出提示消息框
		showMsgDialog : function(title, msg, callback){
			var msgdialog = $('#msgdialog');
			msgdialog.find(".weui_dialog_title,.weui-dialog__title").html(title);
			msgdialog.find(".weui_dialog_bd,.weui-dialog__bd").html(msg);
			
			msgdialog.show().on('click', '.weui_btn_dialog', function () {
	            $('#msgdialog').off('click').hide();
	            if(callback)
	            	callback();
	        });
		},

		// 弹出提示消息框（双按钮）
		showMsgButtonDialog : function(title, msg, callback, btn){
			if(!btn){
				showMsgDialog(title, msg, callback);
				return;
			}
			
			var msgdialog = $('#msgdialog2');
			msgdialog.find(".weui_dialog_title,.weui-dialog__title").html(title);
			msgdialog.find(".weui_dialog_bd,.weui-dialog__bd").html(msg);
			msgdialog.find(".weui-dialog__btn_primary").html(btn.text || "继续");
			
			msgdialog.on('click', '.weui-dialog__btn_default', function() {
				msgdialog.off('click').hide();
	            if(callback)
	            	callback();
	        }).on('click', '.weui-dialog__btn_primary', function() {
	            if(btn.url)
	            	location.href=btn.url;
	        });
			
			msgdialog.show();
		}
	};
	
	this.view.init();
})();

